<script setup>
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue';
import InputError from '@/Components/InputError.vue';
import InputLabel from '@/Components/InputLabel.vue';
import PrimaryButton from '@/Components/PrimaryButton.vue';
import TextInput from '@/Components/TextInput.vue';
import { Head, Link, useForm } from '@inertiajs/vue3';
import { ref } from 'vue';

const props = defineProps({
    bar: Object,
});

const form = useForm({
    title: '',
    content: '',
    images: [],
});

const previewImages = ref([]);

const handleImageChange = (event) => {
    const files = Array.from(event.target.files || []);
    if (files.length + form.images.length > 9) {
        alert('最多只能上传 9 张图片');
        return;
    }

    files.forEach(file => {
        if (file instanceof File) {
            form.images.push(file);
            const reader = new FileReader();
            reader.onload = (e) => {
                previewImages.value.push(e.target.result);
            };
            reader.readAsDataURL(file);
        }
    });
};

const removeImage = (index) => {
    form.images.splice(index, 1);
    previewImages.value.splice(index, 1);
};

const submit = () => {
    form.post(route('posts.store', { bar: props.bar.slug }), {
        forceFormData: true,
        onSuccess: () => {
            form.reset();
            previewImages.value = [];
        },
    });
};
</script>

<template>
    <Head title="发布新帖子" />

    <AuthenticatedLayout>
        <div class="max-w-4xl mx-auto">
            <!-- 发帖表单卡片 -->
            <div class="bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm">
                <div class="px-6">
                    <h1 class="text-3xl font-bold mb-2">发布新帖子</h1>
                    <p class="text-muted-foreground">在 <strong>{{ bar.name }}</strong> 中发布你的想法</p>
                </div>

                <div class="px-6">
                    <form @submit.prevent="submit" class="space-y-6">
                        <!-- 帖子标题 -->
                        <div class="space-y-2">
                            <InputLabel for="title" value="标题" />
                            <TextInput
                                id="title"
                                type="text"
                                class="mt-1 block w-full"
                                v-model="form.title"
                                required
                                autofocus
                                autocomplete="off"
                                placeholder="请输入帖子标题（5-100个字符）"
                            />
                            <InputError class="mt-2" :message="form.errors.title" />
                        </div>

                        <!-- 帖子内容 -->
                        <div class="space-y-2">
                            <InputLabel for="content" value="内容" />
                            <textarea
                                id="content"
                                class="w-full px-3 py-2 border border-input rounded-md bg-transparent text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 resize-none"
                                v-model="form.content"
                                rows="12"
                                required
                                placeholder="分享你的想法、问题或经验...支持 Markdown 格式"
                            ></textarea>
                            <InputError class="mt-2" :message="form.errors.content" />
                            <p class="text-xs text-muted-foreground">支持 Markdown 格式，支持上传图片</p>
                        </div>

                        <!-- 图片上传 -->
                        <div class="space-y-2">
                            <InputLabel for="images" value="添加图片（可选，最多 9 张）" />
                            <div class="border-2 border-dashed border-input rounded-lg p-4">
                                <label class="flex flex-col items-center justify-center cursor-pointer hover:bg-accent/50 transition-colors rounded-lg p-4">
                                    <svg class="h-8 w-8 text-muted-foreground mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                                    </svg>
                                    <span class="text-sm text-muted-foreground">点击上传或拖拽图片到此处</span>
                                    <span class="text-xs text-muted-foreground mt-1">支持 JPG、PNG 格式，最多 9 张</span>
                                    <input
                                        id="images"
                                        type="file"
                                        multiple
                                        accept="image/*"
                                        class="hidden"
                                        @change="handleImageChange"
                                    />
                                </label>
                            </div>
                            <InputError class="mt-2" :message="form.errors.images" />
                            <InputError v-for="(error, index) in form.errors['images.*']" :key="index" class="mt-2" :message="error" />

                            <!-- 图片预览 -->
                            <div v-if="previewImages.length" class="grid grid-cols-3 gap-4 mt-4">
                                <div v-for="(image, index) in previewImages" :key="index" class="relative group">
                                    <img :src="image" class="w-full h-32 object-cover rounded-lg border border-input" />
                                    <button
                                        type="button"
                                        @click="removeImage(index)"
                                        class="absolute top-1 right-1 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-xs opacity-0 group-hover:opacity-100 transition-opacity"
                                    >
                                        ×
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- 提示信息 -->
                        <div class="bg-muted border border-border rounded-lg p-4">
                            <h3 class="text-sm font-medium mb-2">发帖须知</h3>
                            <ul class="text-xs text-muted-foreground space-y-1 list-disc list-inside">
                                <li>请确保内容符合贴吧规范，不得发布违法违规内容</li>
                                <li>发帖前请先搜索，避免发布重复内容</li>
                                <li>优质内容有机会被设为精华帖</li>
                            </ul>
                        </div>

                        <!-- 提交按钮 -->
                        <div class="flex items-center justify-end gap-4 pt-6 border-t">
                            <Link
                                :href="route('bars.show', bar.slug)"
                                class="inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all border bg-background shadow-sm hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2"
                            >
                                取消
                            </Link>
                            <PrimaryButton :disabled="form.processing">发布帖子</PrimaryButton>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </AuthenticatedLayout>
</template>

